<template>
  <div class="dashboard-container">
    <!-- 欢迎卡片 -->
    <div class="welcome-card">
      <div class="welcome-content">
        <h1 class="welcome-title">欢迎回来 👋</h1>
        <p class="welcome-subtitle">这是您的工作台，开始您的高效工作</p>
      </div>
      <div class="welcome-info">
        <div class="info-item">
          <el-icon class="info-icon"><Calendar /></el-icon>
          <span>{{ currentDate }}</span>
        </div>
        <div class="info-item">
          <el-icon class="info-icon"><Clock /></el-icon>
          <span>{{ currentTime }}</span>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card" v-for="stat in stats" :key="stat.title">
        <div class="stat-icon" :style="{ background: stat.gradient }">
          <el-icon><component :is="stat.icon" /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-title">{{ stat.title }}</div>
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-footer">
            <div class="stat-trend" :class="stat.trend > 0 ? 'up' : 'down'">
              <el-icon><component :is="stat.trend > 0 ? CaretTop : CaretBottom" /></el-icon>
              <span>{{ Math.abs(stat.trend) }}%</span>
            </div>
            <span class="stat-label">较上周</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 访问趋势 -->
      <div class="chart-card">
        <div class="card-header">
          <div class="header-left">
            <h3 class="card-title">访问趋势</h3>
            <span class="card-subtitle">最近7天数据</span>
          </div>
          <el-radio-group v-model="visitType" size="small">
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="month">月</el-radio-button>
          </el-radio-group>
        </div>
        <div class="card-body">
          <div ref="visitChartRef" class="chart" style="height: 300px;"></div>
        </div>
      </div>

      <!-- 销售数据 -->
      <div class="chart-card">
        <div class="card-header">
          <div class="header-left">
            <h3 class="card-title">销售数据</h3>
            <span class="card-subtitle">各类目销售额</span>
          </div>
        </div>
        <div class="card-body">
          <div ref="salesChartRef" class="chart" style="height: 300px;"></div>
        </div>
      </div>

      <!-- 用户分布 -->
      <div class="chart-card">
        <div class="card-header">
          <div class="header-left">
            <h3 class="card-title">用户分布</h3>
            <span class="card-subtitle">按地区统计</span>
          </div>
        </div>
        <div class="card-body">
          <div ref="userChartRef" class="chart" style="height: 300px;"></div>
        </div>
      </div>

      <!-- 任务完成率 -->
      <div class="chart-card">
        <div class="card-header">
          <div class="header-left">
            <h3 class="card-title">任务完成率</h3>
            <span class="card-subtitle">本月统计</span>
          </div>
        </div>
        <div class="card-body">
          <div ref="taskChartRef" class="chart" style="height: 300px;"></div>
        </div>
      </div>
    </div>

    <!-- 快捷操作和最新动态 -->
    <div class="bottom-grid">
      <!-- 快捷操作 -->
      <div class="quick-actions-card">
        <div class="card-header">
          <h3 class="card-title">快捷操作</h3>
        </div>
        <div class="card-body">
          <div class="actions-grid">
            <div class="action-item" v-for="action in quickActions" :key="action.title">
              <div class="action-icon" :style="{ background: action.color }">
                <el-icon><component :is="action.icon" /></el-icon>
              </div>
              <span class="action-title">{{ action.title }}</span>
            </div>
          </div>
        </div>
      </div>

    <!-- 权限测试区域 -->
    <div class="permission-test-card">
      <div class="card-header">
        <h3 class="card-title">权限测试</h3>
        <el-tag type="info">测试权限控制</el-tag>
      </div>
      <div class="card-body">
        <div class="permission-actions">
          <el-button type="primary" @click="testSystemPermission">
            测试系统管理权限
          </el-button>
          <el-button type="success" @click="testContentPermission">
            测试内容管理权限
          </el-button>
          <el-button type="warning" @click="testNonExistentPage">
            测试不存在页面
          </el-button>
        </div>
        <div class="permission-info">
          <p><strong>当前用户权限：</strong></p>
          <ul>
            <li v-for="route in userRoutes" :key="route.path">
              {{ route.title }} ({{ route.path }})
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 最新动态 -->
    <div class="activity-card">
      <div class="card-header">
        <h3 class="card-title">最新动态</h3>
      </div>
      <div class="card-body">
        <div class="activity-list">
          <div class="activity-item" v-for="(activity, index) in activities" :key="index">
            <div class="activity-timeline">
              <div class="timeline-dot" :style="{ background: activity.color }"></div>
              <div class="timeline-line" v-if="index < activities.length - 1"></div>
            </div>
            <div class="activity-content">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>

<script>
export default {
  name: '_dashboard'
}
</script>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';
import {
  Calendar,
  Clock,
  User,
  Document,
  ChatDotRound,
  Star,
  CaretTop,
  CaretBottom,
  Plus,
  Edit,
  Upload,
  Download,
  DataAnalysis,
  Setting
} from '@element-plus/icons-vue';

// 时间显示
const currentTime = ref('');
const currentDate = ref('');

const updateTime = () => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  currentTime.value = `${hours}:${minutes}:${seconds}`;
  
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
  const weekday = weekdays[now.getDay()];
  currentDate.value = `${year}年${month}月${day}日 星期${weekday}`;
};

let timer = null;

onMounted(() => {
  updateTime();
  timer = setInterval(updateTime, 1000);
  
  nextTick(() => {
    initCharts();
  });
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
  // 销毁图表
  [visitChartRef, salesChartRef, userChartRef, taskChartRef].forEach(ref => {
    if (ref.value) {
      const instance = echarts.getInstanceByDom(ref.value);
      if (instance) instance.dispose();
    }
  });
});

// 统计数据
const stats = [
  {
    title: '总用户数',
    value: '8,246',
    trend: 12.5,
    icon: User,
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    title: '文档数量',
    value: '1,523',
    trend: 8.3,
    icon: Document,
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
  },
  {
    title: '消息数量',
    value: '652',
    trend: -3.2,
    icon: ChatDotRound,
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
  },
  {
    title: '收藏数量',
    value: '328',
    trend: 15.8,
    icon: Star,
    gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
  }
];

// 快捷操作
const quickActions = [
  { title: '新建文档', icon: Plus, color: '#667eea' },
  { title: '编辑内容', icon: Edit, color: '#f093fb' },
  { title: '上传文件', icon: Upload, color: '#4facfe' },
  { title: '导出数据', icon: Download, color: '#43e97b' },
  { title: '数据分析', icon: DataAnalysis, color: '#fa709a' },
  { title: '系统设置', icon: Setting, color: '#feca57' },
];

// 最新动态
const activities = [
  { title: '管理员创建了新文档', time: '2分钟前', color: '#667eea' },
  { title: '用户张三上传了文件', time: '15分钟前', color: '#f093fb' },
  { title: '系统完成了数据备份', time: '1小时前', color: '#4facfe' },
  { title: '新用户注册成功', time: '2小时前', color: '#43e97b' },
  { title: '管理员修改了系统配置', time: '3小时前', color: '#feca57' },
];

// 图表refs
const visitChartRef = ref(null);
const salesChartRef = ref(null);
const userChartRef = ref(null);
const taskChartRef = ref(null);
const visitType = ref('week');

// 初始化图表
const initCharts = () => {
  initVisitChart();
  initSalesChart();
  initUserChart();
  initTaskChart();
};

// 访问趋势图表
const initVisitChart = () => {
  if (!visitChartRef.value) return;
  
  const chart = echarts.init(visitChartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        lineStyle: {
          color: '#e0e6f1'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '访问量',
        type: 'line',
        smooth: true,
        data: [120, 200, 150, 280, 320, 250, 380],
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102, 126, 234, 0.5)' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.05)' }
          ])
        },
        lineStyle: {
          width: 3,
          color: '#667eea'
        },
        itemStyle: {
          color: '#667eea',
          borderWidth: 2,
          borderColor: '#fff'
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  };
  
  chart.setOption(option);
  
  // 响应式
  window.addEventListener('resize', () => chart.resize());
};

// 销售数据图表
const initSalesChart = () => {
  if (!salesChartRef.value) return;
  
  const chart = echarts.init(salesChartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['电子产品', '服装', '食品', '图书', '家居', '运动'],
      axisLine: {
        lineStyle: {
          color: '#e0e6f1'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: [320, 280, 250, 180, 220, 190],
        itemStyle: {
          borderRadius: [8, 8, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#f093fb' },
            { offset: 1, color: '#f5576c' }
          ])
        },
        barWidth: '40%'
      }
    ]
  };
  
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
};

// 用户分布图表
const initUserChart = () => {
  if (!userChartRef.value) return;
  
  const chart = echarts.init(userChartRef.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center',
      textStyle: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '用户分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: '北京', itemStyle: { color: '#667eea' } },
          { value: 735, name: '上海', itemStyle: { color: '#f093fb' } },
          { value: 580, name: '广州', itemStyle: { color: '#4facfe' } },
          { value: 484, name: '深圳', itemStyle: { color: '#43e97b' } },
          { value: 300, name: '其他', itemStyle: { color: '#feca57' } }
        ]
      }
    ]
  };
  
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
};

// 任务完成率图表
const initTaskChart = () => {
  if (!taskChartRef.value) return;
  
  const chart = echarts.init(taskChartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    legend: {
      top: '0%',
      textStyle: {
        color: '#606266'
      }
    },
    xAxis: {
      type: 'category',
      data: ['第1周', '第2周', '第3周', '第4周'],
      axisLine: {
        lineStyle: {
          color: '#e0e6f1'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: '{value}%',
        color: '#606266'
      }
    },
    series: [
      {
        name: '计划任务',
        type: 'bar',
        data: [85, 90, 78, 92],
        itemStyle: {
          borderRadius: [8, 8, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: '#00f2fe' }
          ])
        },
        barWidth: '25%'
      },
      {
        name: '已完成',
        type: 'bar',
        data: [75, 82, 70, 88],
        itemStyle: {
          borderRadius: [8, 8, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#43e97b' },
            { offset: 1, color: '#38f9d7' }
          ])
        },
        barWidth: '25%'
      }
    ]
  };
  
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
};

// 权限测试相关
const router = useRouter();
const userStore = useUserStore();

// 获取用户路由权限
const userRoutes = computed(() => {
  return userStore.dynamicRoutes || [];
});

// 测试系统管理权限
const testSystemPermission = () => {
  router.push('/system');
};

// 测试内容管理权限
const testContentPermission = () => {
  router.push('/content');
};

// 测试不存在页面
const testNonExistentPage = () => {
  router.push('/non-existent-page');
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 0;
}

/* 欢迎卡片 */
.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 32px 40px;
  margin-bottom: 24px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.25);
  position: relative;
  overflow: hidden;
}

.welcome-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -10%;
  width: 300px;
  height: 300px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  border-radius: 50%;
}

.welcome-title {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 8px 0;
  position: relative;
  z-index: 1;
}

.welcome-subtitle {
  font-size: 16px;
  opacity: 0.95;
  margin: 0;
  position: relative;
  z-index: 1;
}

.welcome-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  position: relative;
  z-index: 1;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.15);
  padding: 10px 20px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.info-icon {
  font-size: 18px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  gap: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, var(--hover-color, #667eea), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border-color: #e8eaed;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
  font-weight: 400;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1;
}

.stat-footer {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-trend {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  font-weight: 600;
  padding: 4px 10px;
  border-radius: 6px;
}

.stat-trend.up {
  color: #43e97b;
  background: rgba(67, 233, 123, 0.1);
}

.stat-trend.down {
  color: #f5576c;
  background: rgba(245, 87, 108, 0.1);
}

.stat-label {
  font-size: 12px;
  color: #c0c4cc;
}

/* 图表网格 */
.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-color: #e8eaed;
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-subtitle {
  font-size: 12px;
  color: #909399;
}

.card-body {
  padding: 24px;
}

.chart {
  width: 100%;
}

/* 底部网格 */
.bottom-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

/* 快捷操作 */
.quick-actions-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.action-item:hover {
  background: #f8f9fa;
  transform: translateY(-2px);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 22px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-title {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

/* 最新动态 */
.activity-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
  overflow: hidden;
}

.activity-list {
  display: flex;
  flex-direction: column;
}

.activity-item {
  display: flex;
  gap: 16px;
  padding: 16px 0;
}

.activity-item:not(:last-child) {
  border-bottom: 1px solid #f5f5f5;
}

.activity-timeline {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.timeline-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  flex-shrink: 0;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.timeline-line {
  flex: 1;
  width: 2px;
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.3) 0%, rgba(102, 126, 234, 0.05) 100%);
  margin: 4px 0;
  min-height: 20px;
}

.activity-content {
  flex: 1;
  padding-top: 2px;
}

.activity-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 500;
}

.activity-time {
  font-size: 12px;
  color: #c0c4cc;
}

/* 权限测试卡片 */
.permission-test-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.permission-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.permission-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.permission-info p {
  margin: 0 0 12px 0;
  color: #303133;
  font-weight: 500;
}

.permission-info ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
}

.permission-info li {
  margin-bottom: 4px;
  font-size: 14px;
}

/* 响应式 */
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .bottom-grid {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .welcome-card {
    flex-direction: column;
    gap: 20px;
  }
  
  .welcome-info {
    width: 100%;
  }
}
</style>
